exports.route = function (app, tool) {
	
	// 激活码生成函数
	function generateActivationCode(membershipType) {
		// 类型映射
		const typeMap = {
			'WEEKLY': 'W',
			'MONTHLY': 'M', 
			'YEARLY': 'Y'
		};
		
		// 生成序号（可以从数据库获取全局计数）
		const sequence = Math.floor(Math.random() * 999) + 1;
		const sequenceStr = sequence.toString().padStart(3, '0');
		
		// 字符集（排除易混淆字符）
		const chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
		
		// 生成随机字符串
		function randomString(length) {
			let result = '';
			for (let i = 0; i < length; i++) {
				result += chars.charAt(Math.floor(Math.random() * chars.length));
			}
			return result;
		}
		
		// 构建激活码
		const typeCode = typeMap[membershipType] || 'M';
		const random1 = randomString(4);
		const random2 = randomString(4);
		
		return `VTK-${typeCode}${sequenceStr}-${random1}-${random2}`;
	}











	/**
	 * @api {GET} /activation_codes/list 激活码列表
	 * @apiName GetActivationList
	 * @apiGroup Activation
	 * @apiDescription 获取激活码列表（管理功能）
	 */
	app.get(['/activation_codes/list'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		
		var req_params = req.query;
		
		var status = req_params.status || '';
		var membership_type = req_params.membership_type || '';
		var bound_mac_id = req_params.bound_mac_id || '';
		var batch_id = req_params.batch_id || '';
		var limit = parseInt(req_params.limit || 50);
		var offset = parseInt(req_params.offset || 0);
		
		var sqls = [];
		var params = [];
		
		if (status) {
			sqls.push("status = ?");
			params.push(status);
		}
		
		if (membership_type) {
			sqls.push("JSON_EXTRACT(config_data, '$.membership_type') = ?");
			params.push(membership_type);
		}
		
		if (bound_mac_id) {
			sqls.push("bound_mac_id = ?");
			params.push(bound_mac_id);
		}
		
		if (batch_id) {
			sqls.push("JSON_EXTRACT(config_data, '$.batch_id') = ?");
			params.push(batch_id);
		}
		
		var whereClause = sqls.length > 0 ? 'WHERE ' + sqls.join(' AND ') : '';
		
		try {
			var result = await tool.mysql_db.query(`
				SELECT 
					id, code, config_data, status, bound_mac_id, 
					UNIX_TIMESTAMP(created_at) as created_at, 
					UNIX_TIMESTAMP(activated_at) as activated_at,
					CASE 
						WHEN activated_at IS NOT NULL THEN 
							(UNIX_TIMESTAMP(activated_at) + JSON_EXTRACT(config_data, '$.duration_days') * 24 * 3600)
						ELSE NULL 
					END as expires_at
				FROM activation_codes 
				${whereClause}
				ORDER BY created_at DESC 
				LIMIT ${limit} OFFSET ${offset}
			`, params);
			
			// 格式化返回数据
			var formatted_result = result.map(item => {
				var config_data = JSON.parse(item.config_data);
				return {
					id: item.id,
					code: item.code,
					config_data: item.config_data, // 包含完整的config_data用于前端计算
					membership_type: config_data.membership_type,
					duration_days: config_data.duration_days,
					status: item.status,
					bound_mac_id: item.bound_mac_id,
					created_at: item.created_at,
					activated_at: item.activated_at,
					expires_at: item.expires_at,
					created_by: config_data.created_by,
					batch_id: config_data.batch_id || '',
					is_renewal: config_data.is_renewal || false,
					usage_limit: config_data.usage_limit || 1,
					used_count: config_data.used_count || 0,
					usage_history: config_data.usage_history || [], // 添加使用历史
					simplified_mode: config_data.simplified_mode || false // 添加简化模式标识
				};
			});
			
			res.send({
				success: true,
				data: {
					list: formatted_result,
					count: formatted_result.length
				}
			});
			
		} catch (e) {
			console.error('查询激活码列表失败:', e);
			res.send({
				success: false,
				error: 'QUERY_FAILED',
				message: '查询失败'
			});
		}
	});



	/**
	 * @api {POST} /activation_codes/cleanup 清理数据
	 * @apiName CleanupCodes
	 * @apiGroup Activation
	 * @apiDescription 清理无效数据（预留接口，激活码本身不会过期）
	 */
	app.post(['/activation_codes/cleanup'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		
		try {
			// 激活码本身不会过期，这里可以做一些数据清理工作
			// 比如清理一些无效的记录等
			
			res.send({
				success: true,
				data: {
					updated_count: 0
				},
				message: '清理完成（激活码本身不会过期）'
			});
			
		} catch (e) {
			console.error('清理数据失败:', e);
			res.send({
				success: false,
				error: 'CLEANUP_FAILED',
				message: '清理失败'
			});
		}
	});

	/**
	 * @api {GET} /activation_codes/stats 激活码统计
	 * @apiName GetActivationStats
	 * @apiGroup Activation
	 * @apiDescription 获取激活码统计信息
	 */
	app.get(['/activation_codes/stats'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		
		try {
			// 按状态统计
			var statusStats = await tool.mysql_db.query(`
				SELECT status, COUNT(*) as count 
				FROM activation_codes 
				GROUP BY status
			`);
			
			// 按会员类型统计
			var typeStats = await tool.mysql_db.query(`
				SELECT 
					JSON_EXTRACT(config_data, '$.membership_type') as membership_type,
					COUNT(*) as count 
				FROM activation_codes 
				GROUP BY JSON_EXTRACT(config_data, '$.membership_type')
			`);
			
			// 今日激活统计
			var todayStats = await tool.mysql_db.query(`
				SELECT COUNT(*) as today_activated 
				FROM activation_codes 
				WHERE DATE(activated_at) = CURDATE() AND status = 'ACTIVATED'
			`);
			
			res.send({
				success: true,
				data: {
					status_stats: statusStats,
					type_stats: typeStats,
					today_activated: todayStats[0]?.today_activated || 0
				}
			});
			
		} catch (e) {
			console.error('获取统计信息失败:', e);
			res.send({
				success: false,
				error: 'STATS_FAILED',
				message: '获取统计信息失败'
			});
		}
	});

	/**
	 * @api {POST} /activation_codes/invalidate 手动失效激活码
	 * @apiName InvalidateActivationCode
	 * @apiGroup Activation
	 * @apiDescription 运营手动失效单个激活码
	 */
	app.post(['/activation_codes/invalidate'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var req_params = Object.assign(req.body, req.query);
		
		var code = req_params.code;
		var reason = req_params.reason || 'MANUAL_INVALIDATION';
		var operator = req_params.operator || 'admin';
		
		if (!code) {
			return res.send({
				success: false,
				error: 'MISSING_CODE',
				message: '激活码不能为空'
			});
		}
		
		if (!operator) {
			return res.send({
				success: false,
				error: 'MISSING_OPERATOR',
				message: '操作员标识不能为空'
			});
		}
		
		try {
			// 查询激活码
			var result = await tool.mysql_db.query(
				"SELECT id, config_data, status, bound_mac_id FROM activation_codes WHERE code = ? LIMIT 1",
				[code]
			);
			
			if (result.length === 0) {
				return res.send({
					success: false,
					error: 'CODE_NOT_FOUND',
					message: '激活码不存在'
				});
			}
			
			var activation_record = result[0];
			
			// 检查激活码状态是否可以失效
			if (activation_record.status === 'EXPIRED') {
				return res.send({
					success: false,
					error: 'ALREADY_EXPIRED',
					message: '激活码已过期'
				});
			}
			
			if (activation_record.status === 'SUPERSEDED') {
				return res.send({
					success: false,
					error: 'ALREADY_INVALIDATED',
					message: '激活码已失效'
				});
			}
			
			// 更新配置数据，记录失效信息
			var config_data = JSON.parse(activation_record.config_data);
			config_data.invalidated_by = operator;
			config_data.invalidated_reason = reason;
			config_data.invalidated_at = Math.floor(Date.now() / 1000);
			
			// 更新激活码状态为失效
			await tool.mysql_db.query(
				"UPDATE activation_codes SET status = 'SUPERSEDED', config_data = ? WHERE code = ?",
				[JSON.stringify(config_data), code]
			);
			
			res.send({
				success: true,
				data: {
					code: code,
					previous_status: activation_record.status,
					invalidated_by: operator,
					invalidated_reason: reason
				},
				message: '激活码失效成功'
			});
			
		} catch (e) {
			console.error('失效激活码失败:', e);
			res.send({
				success: false,
				error: 'INVALIDATION_FAILED',
				message: '失效操作失败'
			});
		}
	});

	/**
	 * @api {POST} /activation_codes/batch_invalidate 批量失效激活码
	 * @apiName BatchInvalidateActivationCodes
	 * @apiGroup Activation
	 * @apiDescription 运营批量失效激活码
	 */
	app.post(['/activation_codes/batch_invalidate'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var req_params = Object.assign(req.body, req.query);
		
		var codes = req_params.codes; // 激活码数组
		var batch_id = req_params.batch_id; // 批次ID
		var membership_type = req_params.membership_type; // 会员类型
		var status = req_params.status; // 当前状态
		var created_after = req_params.created_after; // 创建开始时间
		var created_before = req_params.created_before; // 创建结束时间
		var reason = req_params.reason || 'BATCH_MANUAL_INVALIDATION';
		var operator = req_params.operator || 'admin';
		
		if (!operator) {
			return res.send({
				success: false,
				error: 'MISSING_OPERATOR',
				message: '操作员标识不能为空'
			});
		}
		
		try {
			var sqls = [];
			var params = [];
			
			// 构建查询条件
			if (codes && codes.length > 0) {
				// 按激活码列表
				var placeholders = codes.map(() => '?').join(',');
				sqls.push(`code IN (${placeholders})`);
				params.push(...codes);
			} else if (batch_id) {
				// 按批次ID
				sqls.push("JSON_EXTRACT(config_data, '$.batch_id') = ?");
				params.push(batch_id);
			} else {
				// 按条件筛选
				if (membership_type) {
					sqls.push("JSON_EXTRACT(config_data, '$.membership_type') = ?");
					params.push(membership_type);
				}
				
				if (status) {
					sqls.push("status = ?");
					params.push(status);
				}
				
				if (created_after) {
					sqls.push("created_at >= ?");
					params.push(created_after);
				}
				
				if (created_before) {
					sqls.push("created_at <= ?");
					params.push(created_before);
				}
			}
			
			// 只处理可以失效的状态
			sqls.push("status IN ('GENERATED', 'ACTIVATED')");
			
			if (sqls.length === 1) { // 只有状态条件
				return res.send({
					success: false,
					error: 'INSUFFICIENT_CONDITIONS',
					message: '请提供具体的筛选条件'
				});
			}
			
			var whereClause = sqls.join(' AND ');
			
			// 开始事务
			await tool.mysql_db.query("BEGIN");
			
			try {
				// 先查询要失效的激活码
				var targetCodes = await tool.mysql_db.query(`
					SELECT id, code, config_data, status 
					FROM activation_codes 
					WHERE ${whereClause}
				`, params);
				
				if (targetCodes.length === 0) {
					await tool.mysql_db.query("ROLLBACK");
					return res.send({
						success: false,
						error: 'NO_CODES_FOUND',
						message: '没有找到符合条件的激活码'
					});
				}
				
				var invalidated_count = 0;
				var invalidated_at = Math.floor(Date.now() / 1000);
				
				// 批量更新激活码状态
				for (let codeRecord of targetCodes) {
					var config_data = JSON.parse(codeRecord.config_data);
					config_data.invalidated_by = operator;
					config_data.invalidated_reason = reason;
					config_data.invalidated_at = invalidated_at;
					
					await tool.mysql_db.query(
						"UPDATE activation_codes SET status = 'SUPERSEDED', config_data = ? WHERE id = ?",
						[JSON.stringify(config_data), codeRecord.id]
					);
					
					invalidated_count++;
				}
				
				// 提交事务
				await tool.mysql_db.query("COMMIT");
				
				res.send({
					success: true,
					data: {
						total_processed: targetCodes.length,
						invalidated_count: invalidated_count,
						invalidated_by: operator,
						invalidated_reason: reason
					},
					message: `批量失效成功，共处理 ${targetCodes.length} 个激活码`
				});
				
			} catch (e) {
				// 回滚事务
				await tool.mysql_db.query("ROLLBACK");
				throw e;
			}
			
		} catch (e) {
			console.error('批量失效激活码失败:', e);
			res.send({
				success: false,
				error: 'BATCH_INVALIDATION_FAILED',
				message: '批量失效操作失败'
			});
		}
	});

	// ==================== 简化版兑换码系统 ====================

	/**
	 * @api {POST} /activation_codes/generate_simple 简化版生成兑换码
	 * @apiName GenerateSimpleActivationCode
	 * @apiGroup ActivationSimplified
	 * @apiDescription 生成支持多次使用的简化兑换码，直接操作 zww_member 表
	 */
	app.post(['/activation_codes/generate_simple'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var req_params = Object.assign(req.body, req.query);
		
		var membership_type = req_params.membership_type || 'MONTHLY';
		var duration_days = parseInt(req_params.duration_days || 30);
		var usage_limit = parseInt(req_params.usage_limit || 1); // 使用次数限制
		var count = parseInt(req_params.count || 1);
		var created_by = req_params.created_by || 'admin';
		var notes = req_params.notes || '';
		var track = req_params.track || 'default';
		var item_id = req_params.item_id || 'tomp3';
		
		try {
			var generated_codes = [];
			
			for (let i = 0; i < count; i++) {
				var code = generateActivationCode(membership_type);
				
				// 确保激活码唯一性
				var existing = await tool.mysql_db.query("SELECT id FROM activation_codes WHERE code = ?", [code]);
				while (existing.length > 0) {
					code = generateActivationCode(membership_type);
					existing = await tool.mysql_db.query("SELECT id FROM activation_codes WHERE code = ?", [code]);
				}
				
				var config_data = {
					membership_type: membership_type,
					duration_days: duration_days,
					usage_limit: usage_limit,
					used_count: 0,
					created_by: created_by,
					notes: notes,
					track: track,
					item_id: item_id,
					simplified_mode: true // 标记为简化模式
				};
				
				var created_at = Math.floor(Date.now() / 1000);
				await tool.mysql_db.query(
					"INSERT INTO activation_codes (code, config_data, status, created_at) VALUES (?, ?, ?, FROM_UNIXTIME(?))",
					[code, JSON.stringify(config_data), 'GENERATED', created_at]
				);
				
				generated_codes.push({
					code: code,
					membership_type: membership_type,
					duration_days: duration_days,
					usage_limit: usage_limit
				});
			}
			
			res.send({
				success: true,
				data: {
					codes: generated_codes,
					count: generated_codes.length
				},
				message: `成功生成${generated_codes.length}个兑换码`
			});
			
		} catch (e) {
			console.error('生成兑换码失败:', e);
			res.send({
				success: false,
				error: 'GENERATE_FAILED',
				message: '生成兑换码失败'
			});
		}
	});

	/**
	 * @api {POST} /activation_codes/redeem 简化版兑换码兑换
	 * @apiName RedeemActivationCode
	 * @apiGroup ActivationSimplified
	 * @apiDescription 兑换码兑换，直接操作 zww_member 表，支持多次使用
	 */
	app.post(['/activation_codes/redeem'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var req_params = Object.assign(req.body, req.query);
		
		var code = req_params.code;
		var user_id = req_params.user_id || req_params.userId || req_params.android_id;
		var track = req_params.track || 'default';
		var item_id = req_params.item_id || req_params.itemId || 'tomp3';
		
		if (!code || !user_id) {
			return res.send({
				success: false,
				error: 'MISSING_PARAMS',
				message: '兑换码和用户ID不能为空'
			});
		}
		
		try {
			// 开始事务
			await tool.mysql_db.query("BEGIN");
			
			// 查询兑换码
			var result = await tool.mysql_db.query(
				"SELECT id, config_data, status FROM activation_codes WHERE code = ? FOR UPDATE",
				[code]
			);
			
			if (result.length === 0) {
				await tool.mysql_db.query("ROLLBACK");
				return res.send({
					success: false,
					error: 'CODE_NOT_FOUND',
					message: '兑换码不存在'
				});
			}
			
			var activation_record = result[0];
			var config_data = JSON.parse(activation_record.config_data);
			
			// 检查是否为简化版兑换码
			if (!config_data.simplified_mode) {
				await tool.mysql_db.query("ROLLBACK");
				return res.send({
					success: false,
					error: 'NOT_SIMPLIFIED_CODE',
					message: '请使用传统激活码接口'
				});
			}
			
			// 检查兑换码状态
			if (activation_record.status === 'ACTIVATED') {
				// 对于简化版兑换码，如果已达到使用上限，则视为失效
				var used_count = config_data.used_count || 0;
				if (used_count >= config_data.usage_limit) {
					await tool.mysql_db.query("ROLLBACK");
					return res.send({
						success: false,
						error: 'CODE_EXHAUSTED',
						message: '兑换码使用次数已达上限'
					});
				}
			} else if (activation_record.status === 'SUPERSEDED') {
				await tool.mysql_db.query("ROLLBACK");
				return res.send({
					success: false,
					error: 'CODE_SUPERSEDED',
					message: '兑换码已被失效'
				});
			} else if (activation_record.status !== 'GENERATED') {
				await tool.mysql_db.query("ROLLBACK");
				return res.send({
					success: false,
					error: 'CODE_INVALID',
					message: '兑换码状态无效'
				});
			}
			
			// 检查使用次数限制
			var used_count = config_data.used_count || 0;
			if (used_count >= config_data.usage_limit) {
				await tool.mysql_db.query("ROLLBACK");
				return res.send({
					success: false,
					error: 'CODE_EXHAUSTED',
					message: '兑换码使用次数已达上限'
				});
			}
			
			// 使用配置中的 track 和 item_id，如果没有则使用请求参数
			var final_track = config_data.track || track;
			var final_item_id = config_data.item_id || item_id;
			
			// 计算会员到期时间
			var current_time = Math.floor(Date.now() / 1000);
			var new_overtime = current_time + (config_data.duration_days * 24 * 3600);
			
			// 检查用户是否已有会员记录
			var existing_member = await tool.mysql_db.query(
				"SELECT id, overtime FROM zww_member WHERE user_id = ? AND item_id = ? AND track = ?",
				[user_id, final_item_id, final_track]
			);
			
			if (existing_member.length > 0) {
				// 续费：在现有基础上延长
				var current_overtime = existing_member[0].overtime;
				var extend_from = Math.max(current_overtime, current_time);
				new_overtime = extend_from + (config_data.duration_days * 24 * 3600);
				
				await tool.mysql_db.query(
					"UPDATE zww_member SET overtime = ?, num = 999999 WHERE id = ?",
					[new_overtime, existing_member[0].id]
				);
				
				console.log('会员续费成功:', user_id, final_item_id, 'new_overtime:', new_overtime);
			} else {
				// 新开通会员
				var member_data = {
					user_id: user_id,
					track: final_track,
					item_id: final_item_id,
					num: 999999, // 无限次数
					overtime: new_overtime,
					ctime: current_time
				};
				
				var insert_sql = tool.insert_sql('zww_member', member_data);
				await tool.mysql_db.query(insert_sql);
				
				console.log('新会员创建成功:', user_id, final_item_id, 'overtime:', new_overtime);
			}
			
			// 更新兑换码使用次数
			config_data.used_count = used_count + 1;
			config_data.last_used_at = current_time;
			config_data.last_used_by = user_id;
			
			// 记录使用历史
			if (!config_data.usage_history) {
				config_data.usage_history = [];
			}
			config_data.usage_history.push({
				user_id: user_id,
				used_at: current_time,
				usage_count: used_count + 1
			});
			
			// 如果达到使用上限，标记为已用完
			var new_status = config_data.used_count >= config_data.usage_limit ? 'ACTIVATED' : 'GENERATED';
			
			// 更新绑定设备列表（支持多个设备）
			var bound_devices = [];
			if (activation_record.bound_mac_id) {
				// 解析已有的设备ID列表
				bound_devices = activation_record.bound_mac_id.split(',').map(id => id.trim()).filter(id => id);
			}
			
			// 添加当前设备ID（如果还没有）
			if (!bound_devices.includes(user_id)) {
				bound_devices.push(user_id);
			}
			
			// 合并设备ID列表，用逗号分隔
			var bound_devices_string = bound_devices.join(',');
			
			console.log('绑定设备列表更新:', bound_devices_string);
			
			// 更新兑换码状态和绑定设备信息
			await tool.mysql_db.query(
				"UPDATE activation_codes SET config_data = ?, status = ?, bound_mac_id = ? WHERE id = ?",
				[JSON.stringify(config_data), new_status, bound_devices_string, activation_record.id]
			);
			
			// 提交事务
			await tool.mysql_db.query("COMMIT");
			
			res.send({
				success: true,
				data: {
					code: code,
					membership_type: config_data.membership_type,
					duration_days: config_data.duration_days,
					expires_at: new_overtime,
					used_count: config_data.used_count,
					usage_limit: config_data.usage_limit,
					remaining_uses: config_data.usage_limit - config_data.used_count
				},
				message: '兑换成功！会员已激活'
			});
			
		} catch (e) {
			await tool.mysql_db.query("ROLLBACK");
			console.error('兑换码兑换失败:', e);
			res.send({
				success: false,
				error: 'REDEEM_FAILED',
				message: '兑换失败，请稍后重试'
			});
		}
	});

	/**
	 * @api {GET} /zww_member/status 查询会员状态
	 * @apiName GetMembershipStatusSimplified
	 * @apiGroup MembershipSimplified
	 * @apiDescription 基于 zww_member 表查询会员状态
	 */
	app.get(['/zww_member/status'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var user_id = req.query.user_id || req.query.userId || req.query.android_id;
		var track = req.query.track || 'default';
		var item_id = req.query.item_id || req.query.itemId || 'tomp3';
		
		if (!user_id) {
			return res.send({
				success: false,
				error: 'MISSING_USER_ID',
				message: '用户ID不能为空'
			});
		}
		
		try {
			var result = await tool.mysql_db.query(
				"SELECT * FROM zww_member WHERE user_id = ? AND item_id = ? ORDER BY overtime DESC LIMIT 5",
				[user_id, item_id]
			);
			
			if (result.length === 0) {
				return res.send({
					success: true,
					data: {
						status: 'INACTIVE',
						is_active: false,
						message: '该用户暂无有效会员'
					}
				});
			}
			
			var member = result[0];
			var current_time = Math.floor(Date.now() / 1000);
			var is_active = member.overtime > current_time && member.num > 0;
			
			res.send({
				success: true,
				data: {
					user_id: member.user_id,
					track: member.track,
					item_id: member.item_id,
					num: member.num,
					overtime: member.overtime,
					expires_at: member.overtime,
					status: is_active ? 'ACTIVE' : 'EXPIRED',
					is_active: is_active,
					remaining_days: is_active ? Math.ceil((member.overtime - current_time) / (24 * 3600)) : 0
				}
			});
			
		} catch (e) {
			console.error('查询会员状态失败:', e);
			res.send({
				success: false,
				error: 'QUERY_FAILED',
				message: '查询失败，请稍后重试'
			});
		}
	});

	/**
	 * @api {POST} /zww_member/renew 会员续费
	 * @apiName RenewMembershipSimplified
	 * @apiGroup MembershipSimplified
	 * @apiDescription 直接操作 zww_member 表进行会员续费
	 */
	app.post(['/zww_member/renew'], async function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header("Access-Control-Allow-Headers", "*");
		res.header("Access-Control-Allow-Methods", "*");
		
		var req_params = Object.assign(req.body, req.query);
		
		var user_id = req_params.user_id || req_params.userId;
		var track = req_params.track || 'default';
		var item_id = req_params.item_id || req_params.itemId || 'tomp3';
		var duration_days = parseInt(req_params.duration_days || 30);
		var payment_method = req_params.payment_method || 'APP_PURCHASE';
		
		console.log('调用 renew:', user_id);
		
		if (!user_id) {
			console.log('用户ID不能为空:', user_id);
			return res.send({
				success: false,
				error: 'MISSING_USER_ID',
				message: '用户ID不能为空'
			});
		}
		
		try {
			var current_time = Math.floor(Date.now() / 1000);
			var extend_days = duration_days * 24 * 3600;
			
			// 检查用户是否已有会员记录
			var existing_member = await tool.mysql_db.query(
				"SELECT id, overtime FROM zww_member WHERE user_id = ? AND item_id = ? AND track = ?",
				[user_id, item_id, track]
			);
			
			var new_overtime;
			
			if (existing_member.length > 0) {
				// 续费：在现有基础上延长
				var current_overtime = existing_member[0].overtime;
				var extend_from = Math.max(current_overtime, current_time);
				new_overtime = extend_from + extend_days;
				
				await tool.mysql_db.query(
					"UPDATE zww_member SET overtime = ?, num = 999999 WHERE id = ?",
					[new_overtime, existing_member[0].id]
				);
				
				console.log('会员续费成功:', user_id, item_id, 'new_overtime:', new_overtime);
			} else {
				// 新开通会员
				new_overtime = current_time + extend_days;
				
				var member_data = {
					user_id: user_id,
					track: track,
					item_id: item_id,
					num: 999999,
					overtime: new_overtime,
					ctime: current_time
				};
				
				var insert_sql = tool.insert_sql('zww_member', member_data);
				await tool.mysql_db.query(insert_sql);
				
				console.log('新会员创建成功:', user_id, item_id, 'overtime:', new_overtime);
			}
			
			res.send({
				success: true,
				data: {
					user_id: user_id,
					duration_days: duration_days,
					expires_at: new_overtime,
					payment_method: payment_method
				},
				message: '续费成功！'
			});
			
		} catch (e) {
			console.error('会员续费失败:', e);
			res.send({
				success: false,
				error: 'RENEW_FAILED',
				message: '续费失败，请稍后重试'
			});
		}
	});

};
